import os
import sys

from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *

url: str = "C:\Program Files\Google\Chrome\Application\chrome.exe"


class DlgMain(QDialog):
    def __init__(self, *args, **kwargs):
        global url
        super(DlgMain, self).__init__(*args, **kwargs)
        try:
            with open("location.txt", "r") as file:
                url = file.read()
                print(url)
        except:
            pass
        self.addSystemTray()

    def addSystemTray(self):
        restoreAction = QAction('&编辑软件位置', self)
        qw = QW()
        restoreAction.triggered.connect(lambda: qw.show())
        quitAction = QAction("&退出", self, triggered=self.close)
        self.trayIconMenu = QMenu(self)
        self.trayIconMenu.addAction(restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(quitAction)
        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.activated.connect(self.systemIcon)
        self.trayIcon.setIcon(QIcon("logo.ico"))
        self.setWindowIcon(QIcon("logo.ico"))
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.show()

    def systemIcon(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            try:
                os.startfile(url)
            except:
                QtWidgets.QMessageBox.critical(self, "错误", "请检查软件地址!")


class QW(QWidget):
    def __init__(self):
        super().__init__()
        self.init()

    def init(self):
        global url
        grid = QGridLayout()
        grid.setSpacing(10)
        #grid.addWidget(QLabel('打开软件地址'), 1, 0)
        self.setWindowIcon(QIcon("logo.ico"))
        self.setWindowTitle("打开软件地址")
        self.edit = QLineEdit();
        self.edit.setText(url)
        grid.addWidget(self.edit, 1, 1)
        self.btn = QPushButton("保存", self)
        self.btn.clicked.connect(self.onButtonClick)
        grid.addWidget(self.btn, 1, 2)
        self.setLayout(grid)

    def closeEvent(self, event):
        global url
        event.ignore()
        self.edit.setText(url)
        self.hide()

    def onButtonClick(self, event):
        global url
        if not os.path.exists(self.edit.text()):
            QtWidgets.QMessageBox.critical(self, "错误", "请检查文件地址!")
        else:
            url = self.edit.text()
            with open('location.txt', 'w+') as file:
                file.write(url)
            print(url)
            self.hide()

if __name__ == '__main__':
    qt = QApplication(sys.argv)
    body = DlgMain()
    sys.exit(qt.exec_())
